// pages/cv/cv.js
import { areaList } from '../../miniprogram_npm/miniprogram_npm/@vant/area-data/index'
import util from '../../utils/util'
const db = wx.cloud.database({
  env: 'work1-0g1b3grp436e9236'
})
const app = getApp() // 获取全局APP对象

Page({

    /**
     * 页面的初始数据
     */
    data: {
        realName: '',
        realNameErr: '',
        gender: '',
        genderErr: '',
        eduBg: '',
        eduBgErr: '',
        age: 18,
        ageErr: '',
        phone: '',
        phoneErr: '',
        skill: '',
        skillErr: '',
        workExp: '',
        workExpErr: '',
        selfEval: '',
        selfEvalErr: '',
        showGenderSelection: false,
        showEduBgSelection: false,
        genderSelections: [{
            name: '男'
        }, {
            name: '女',
            color: '#f56c6c'
        }],
        eduBgSelections: [{ 
            name: '小学',
            color: '#76c893'
        }, {
            name: '初中',
            color: '#52b69a'
        }, {
            name: '中专',
            color: '#34a0a4'
        }, {
            name: '高中',
            color: '#168aad'
        }, {
            name: '大专',
            color: '#1a759f'
        }, {
            name: '本科',
            color: '#1e6091'
        }, {
            name: '硕士',
            color: '#184e77'
        }],
        // 弹出操作控
        showCityPick: false,
        areaList,
        curCity: '未知',
        pickCity: '',
        pickCityErr: '',
        // 选择日历
        minDate: new Date(2022, 5, 1).getTime(),
        maxDate: new Date(2023, 0, 1).getTime(),
        showCalendar: false,
        period: '2022-6-1至2022-9-1',
        periodErr: ''
    },

    // 提交所有信息
    submit() {
        wx.showLoading({title: '检查中...'})
        setTimeout(() => {
            wx.hideLoading()
            // 校验表单
            if (!this.checkForm()) {
                util.myToastNone('请检查输入是否有误', 1000)
                return
            } else {
                // 检查是否登录
                const userInfo = wx.getStorageSync('userInfo')
                if(!userInfo) {
                  setTimeout(() => {
                    util.myToastError('请先登录～')
                  }, 600);
                  wx.switchTab({url: '/pages/center/center'})
                  return
                }
                wx.showLoading({title: '正在保存...'})
                setTimeout(async () => {
                    wx.hideLoading()
                    const res = await db.collection('work_cv').where({userId: userInfo.userId}).get()
                    // 该用户从未制作过简历
                    if (res.data.length === 0) {
                      // 保存数据
                      db.collection('work_cv').add({
                        data: {
                            realName: this.data.realName, 
                            gender: this.data.gender, 
                            eduBg: this.data.eduBg, 
                            age: this.data.age, 
                            phone: this.data.phone, 
                            skill: this.data.skill, 
                            workExp: this.data.workExp, 
                            selfEval: this.data.selfEval, 
                            pickCity: this.data.pickCity,
                            beginTime: this.data.period.split('至')[0],
                            endTime: this.data.period.split('至')[0],
                            userId: userInfo.userId
                        }
                      }).then(res => {
                        const id = res._id
                        wx.hideLoading({
                            success: (res) => {
                              // 跳转到查看页面
                              wx.redirectTo({url: '/pages/cv-preview/cv-preview?_id=' + id})
                            },
                          })
                      })
                    } else {
                      const id = res.data[0]._id
                      // 修改用户原来的简历
                      db.collection('work_cv').where({userId: userInfo.userId}).update({
                        data: {
                            realName: this.data.realName, 
                            gender: this.data.gender, 
                            eduBg: this.data.eduBg, 
                            age: this.data.age, 
                            phone: this.data.phone, 
                            skill: this.data.skill, 
                            workExp: this.data.workExp, 
                            selfEval: this.data.selfEval, 
                            pickCity: this.data.pickCity,
                            beginTime: this.data.period.split('至')[0],
                            endTime: this.data.period.split('至')[1],
                            userId: userInfo.userId
                        }
                      }).then(res => {
                        wx.redirectTo({url: '/pages/cv-preview/cv-preview?_id=' + id})
                        wx.hideLoading()
                      })
                    }
                }, 800)
            }
        }, 500)
    },

    // 获取当前地理位置
    getLocation() {
        wx.getLocation({ // 获取当前位置
            type: 'gcj02' // gcj02火星坐标系，用于地图标记点位
        }).then(async res => { // 获取成功
            const {
                latitude,
                longitude
            } = res // 如果传入为空，则使用data内数据
            console.log("经纬度：" + longitude + ", " + latitude)
            await app.call({ // 发起云函数请求
                name: 'location', // 业务为location，获取经纬度信息
                data: { // 传入经纬度信息
                    location: `${latitude},${longitude}`
                },
                load: false // 不显示加载loading，静默执行
            }).then(res => {
                // this.setData({
                //     keyword: res.adinfo.split(',')[2] + res.adinfo.split(',')[3]
                // })
                console.log(res.adinfo.split(',')[3])
                this.setData({curCity: res.adinfo.split(',')[3]})
                if (!this.data.pickCity) {
                    this.setData({pickCity: res.adinfo.split(',')[3]})
                }
            })
        }).catch(e => {
            // 获取失败
            util.myToastNone('获取当前定位失败')
        })
    },

    // 打开选择性别操作框
    showEduBgSelections() {
        this.setData({
            showEduBgSelection: true
        })
    },

    // 关闭选择性别操作框
    onCloseEduBgSelection() {
        this.checkFormEduBg()
        this.setData({ showEduBgSelection: false })
    },

    // 选择性别
    onSelectEduBgSelection(event) {
        console.log(event.detail)
        this.setData({
            eduBg: event.detail.name
        })
    },

    // 日历相关
    onDisplayCalendar() {
        this.setData({ showCalendar: true })
    },
    onCloseCalendar() {
        this.checkFormPeriod()
        this.setData({ showCalendar: false })
        this.selectComponent('#item').toggle(false);
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onConfirmCalendar(event) {
        const [start, end] = event.detail;
        this.setData({
            showCalendar: false,
            period: `${this.formatDate(start)}至${this.formatDate(end)}`,
        })
        this.selectComponent('#item').toggle(false);
    },

    // 选择城市
    confirmCity(e) {
        console.log(e)
        if (e.currentTarget.dataset.city) {
            this.setData({
                pickCity: e.currentTarget.dataset.city
            })
        } else {
            this.setData({
                pickCity: e.detail.values[2].name
            })
        }
        this.onCloseCityPick()
    },

    // 关闭选择城市操作框
    onCloseCityPick() {
        this.setData({ showCityPick: false })
        this.checkFormPickCity()
    },

    // 打开选择城市操作框
    toPickCity() {
        this.setData({ showCityPick: true });
    },

    // 打开选择性别操作框
    showGenderSelections() {
        this.setData({
            showGenderSelection: true
        })
    },

    // 关闭选择性别操作框
    onCloseGenderSelection() {
        this.checkFormGender()
        this.setData({ showGenderSelection: false })
    },

    // 选择性别
    onSelectGenderSelection(event) {
        console.log(event.detail)
        this.setData({
            gender: event.detail.name
        })
    },

    checkFormEduBg() {
        if(!this.data.eduBg) {
            this.setData({eduBgErr: '请选择教育经历'})
            return false
        }
        this.setData({eduBgErr: ''})
        return true
    },

    checkFormPeriod() {
        if(!this.data.period) {
            this.setData({periodErr: '请选择时间段'})
            return false
        }
        this.setData({periodErr: ''})
        return true
    },

    checkFormRealName() {
        let reg=/^[\u4e00-\u9fff]+$/
        if(!this.data.realName) {
            this.setData({realNameErr: '姓名不能为空'})
            return false
        } else if (!reg.test(this.data.realName)) {
            this.setData({realNameErr: '请输入正确的姓名'})
            return false
        }
        this.setData({realNameErr: ''})
        return true
    },

    checkFormGender() {
        if(!this.data.gender) {
            this.setData({genderErr: '请选择性别'})
            return false
        }
        this.setData({genderErr: ''})
        return true
    },

    checkFormAge() {
        if(!this.data.age) {
            this.setData({ageErr: '年龄不能为空'})
            return false
        } else if (this.data.age < 18) {
            this.setData({ageErr: '年龄不能小于18岁'})
            return false
        }
        this.setData({ageErr: ''})
        return true
    },

    checkFormPickCity() {
        if(!this.data.pickCity) {
            this.setData({pickCityErr: '请选择工作城市'})
            return false
        }
        this.setData({pickCityErr: ''})
        return true
    },

    checkFormPhone() {
        let regex = /^(13[0-9]{9})|(15[0-9]{9})|(16[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/
        if(!this.data.phone) {
            this.setData({phoneErr: '电话号码不能为空哦~'})
            return false
        } else if (!regex.test(this.data.phone)) {
            this.setData({phoneErr: '请输入正确的11位电话号码'})
            return false
        }
        this.setData({phoneErr: ''})
        return true
    },

    checkFormWorkExp() {
        if(!this.data.workExp) {
            this.setData({workExpErr: '请填写工作经历'})
            return false
        }
        this.setData({workExpErr: ''})
        return true
    },

    checkFormSkill() {
        if(!this.data.skill) {
            this.setData({skillErr: '请填写工作擅长技能'})
            return false
        }
        this.setData({skillErr: ''})
        return true
    },

    checkFormSelfEval() {
        if(!this.data.selfEval) {
            this.setData({selfEvalErr: '请填写自我评价'})
            return false
        }
        this.setData({selfEvalErr: ''})
        return true
    },

    checkForm() {
        if (this.checkFormRealName() && this.checkFormAge() && this.checkFormGender() && this.checkFormEduBg() 
            && this.checkFormPickCity() && this.checkFormPhone() && this.checkFormPeriod() && this.checkFormWorkExp() 
            && this.checkFormSkill() && this.checkFormSelfEval()) {
            console.log('form true')
            return true
        }
        console.log('form false')
        return false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      util.myLoading('正在加载', 1000)
      this.getLocation()
      // 检查是否登录
      const userInfo = wx.getStorageSync('userInfo')
      db.collection('work_cv').where({userId: userInfo.userId}).get().then(res=>{
        if (res.data.length === 0) return
        // console.log(res.data[0])
        const {realName, gender, eduBg, age, phone, skill, workExp, selfEval, pickCity, beginTime, endTime} = res.data[0]
        this.setData({realName, gender, eduBg, age, phone, skill, workExp, selfEval, pickCity})
        this.setData({period: beginTime + '至' + endTime})
      })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})